#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Wave Relay
# Copyright (C) 2010 Yakovlev Vladimir [nvbn.rm@gmail.com]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from PyQt4 import QtCore, QtGui
from PyQt4.phonon import Phonon
import thread
from random import random
import time



class Player:
    """Player class"""
    current_song = None
    last_song = None
    player = None

    def __init__(self, parent):
        """Initiale player class

        Keyword arguments:
        parent -- Main lass

        Returns: None

        """
        self.parent = parent
        self.player = Phonon.createPlayer(Phonon.MusicCategory)
        self.seeker = Phonon.SeekSlider(self.player)
        self.seeker.setIconVisible(False)
        self.output = Phonon.AudioOutput(self.player)
        self.volume = Phonon.VolumeSlider(self.output)
        self.volume.setFixedWidth(100)
        self.parent.widget.seekPlaceholder.addWidget(self.seeker)
        self.parent.widget.volumePlaceholder.addWidget(self.volume)
        self.player.tickInterval = 100
        QtCore.QObject.connect(self.player, QtCore.SIGNAL('aboutToFinish()'), self.next_preview)
        QtCore.QObject.connect(self.player, QtCore.SIGNAL('finished()'), self.trully_next)



    def scrobble(self, *arg):
        track = self.current_song.get_song(self.parent.lastfm)
        artist = track.get_artist()
        title = track.title
        time_started = time.time() - track.get_duration()
        source = 'SCROBBLE_SOURCE_UNKNOWN'
        mode = 'SCROBBLE_MODE_PLAYED'
        duration = track.get_duration()
        album = track.get_album()
        track_number = '1'
        mbid = track.get_mbid()
        print self.parent.scrobbler.scrobble(artist, title, time_started, source, mode, duration, album, track_number, mbid)

    @QtCore.pyqtSlot()
    def next_preview(self):
        """Do action previosly next song"""
        thread.start_new_thread(self.scrobble, (None, ))
        self.next(True)

    @QtCore.pyqtSlot()
    def trully_next(self):
        """Play next song"""
        try:
            self.play_threaded(self.next_song)
        except:
            self.next()

    @QtCore.pyqtSlot()
    def next(self, preview = False):
        """Set next song w/o or w playing it

        Keyword arguments:
        preview -- Boolean

        Returns: Song

        """
        self.last_song = self.current_song
        random_num = random() * len(self.parent.playlist.playlist)
        get_song = lambda id: self.parent.playlist.playlist[int((id <= len(self.parent.playlist.playlist)\
        and id) or (confs[1] and random_num) or 0)]
        confs = [str(getattr(self.parent.config, element)) == 'True' for element in ('repeat_song', 'repeat', 'random')]
        song = (confs[0] and self.current_song)\
            or (confs[2] and get_song(random_num))\
            or get_song(self.parent.playlist.playlist.index(self.current_song) + 1)
        if preview:
            self.next_song = song
            thread.start_new_thread((lambda song: song.get_url(self.parent.vk)), (self.next_song, ))
        else:
            self.play_threaded(song)

    @QtCore.pyqtSlot()
    def prev(self):
        """Play previos song"""
        self.play_threaded(self.last_song)

    @QtCore.pyqtSlot()
    def play_button(self):
        """Action for play button"""
        if self.player.state() == Phonon.PlayingState:
            self.player.pause()
            self.parent.status(False)
        else:
            try:
                print self.flag
                self.player.play()
            except:
                self.play_threaded(self.parent.playlist.playlist[0])
            self.parent.status(True)

    @QtCore.pyqtSlot()
    def play(self, song):
        """Get id by song from playlist

        Keyword arguments:
        song -- Song

        Returns: None

        """
        self.flag = True
        self.current_song = song
        try:
            url = song.get_url(self.parent.vk)
        except IndexError:
            self.next()#display_error and play next
            return(False)
        try:
            self.player.stop()
        except:
            pass
        for entry in self.parent.playlist.playlist:
            entry.setIcon(0, self.parent.widget.icon_noplay)
        self.parent.status(True)
        self.player.setCurrentSource(Phonon.MediaSource(QtCore.QUrl(url)))
        self.player.play()

    @QtCore.pyqtSlot()
    def play_threaded(self, song):
        """Start new thread for playing song

        Keyword arguments:
        song -- Song

        Returns: None

        """
        thread.start_new_thread((lambda song: self.play(song)), (song, ))

    @QtCore.pyqtSlot()
    def love_button(self):
        """Add song to favourite on last.fm"""
        self.current_song.get_song(self.parent.lastfm).love()